
const cloud = require('wx-server-sdk');
const got = require('got');
const cheerio = require('cheerio');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const articlesCollection = db.collection('articles');

// 从HTML中提取文章信息
async function extractArticleInfo(html) {
  const $ = cheerio.load(html);
  
  // 提取标题
  const title = $('h1.rich_media_title').text().trim();
  
  // 提取封面图片
  let coverImg = '';
  // 尝试从文章内容中找到第一张图片作为封面
  const firstImg = $('div.rich_media_content img').first();
  if (firstImg.length > 0) {
    coverImg = firstImg.attr('data-src') || firstImg.attr('src');
  }
  
  // 提取摘要
  let summary = '';
  const firstParagraph = $('div.rich_media_content p').first();
  if (firstParagraph.length > 0) {
    summary = firstParagraph.text().trim();
  }
  
  // 提取文章内容
  const content = $('div.rich_media_content').html() || '';
  
  return {
    title,
    coverImg,
    summary,
    content
  };
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { url } = event;
  
  try {
    // 验证URL
    if (!url || !url.includes('mp.weixin.qq.com')) {
      throw new Error('请输入有效的微信公众号文章链接');
    }

    // 获取文章HTML内容
    const response = await got(url);
    const html = response.body;

    // 提取文章信息
    const articleInfo = await extractArticleInfo(html);
    
    // 验证必要字段
    if (!articleInfo.title) {
      throw new Error('无法提取文章标题');
    }

    // 添加其他必要字段
    const now = new Date();
    const article = {
      ...articleInfo,
      createTime: now,
      updateTime: now,
      readCount: 0,
      collectCount: 0,
      sourceUrl: url
    };

    // 保存到数据库
    const result = await articlesCollection.add({
      data: article
    });

    return {
      success: true,
      message: '文章导入成功',
      data: {
        _id: result._id,
        title: article.title
      }
    };

  } catch (error) {
    console.error('导入文章失败:', error);
    return {
      success: false,
      message: error.message || '导入文章失败，请稍后重试'
    };
  }
};